<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/3
 * Time: 10:53
 */

namespace app\applet\model;


use think\Db;
use think\Exception;
use WeixinPay\WeixinPay;
class ShopPay
{
    //
    public function getInfo($input)
    {
        $info=DB::name("store_apply")->where(['sa_id'=>$input['store_id']])->field("sa_id store_id,company_name")->find();
        $settle_ratio=DB::name("store_detail")->where(['sa_id'=>$input['store_id']])->value("settle_ratio");
        $info['settle_ratio']=$settle_ratio;
        $asset=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->field("score,coin")->find();
        $info['mem_score']=$asset['score'];
        $info['mem_coin']=$asset['coin'];
        return $info;
    }

    /**
     * 创建到店支付订单
     */
    public function createOrder($input){
        $store_id=$input['store_id'];
        $pay_amount=$input['pay_amount'];
        $rebate_rate=DB::name("store_detail")->where(['sa_id'=>$store_id])->value("settle_ratio");
        $pay_method=$input['pay_method'];
        $member_id=$input['member_id'];
         if($pay_amount<=0){
             returnJson(-2003,'消费金额格式错误');
         }
        if($rebate_rate<=0){
            returnJson(-2003,'返利比例格式错误');
        }
        $pay_method=explode(",",$pay_method);
        //获取会员资产
        $asset=Db::name("member_asset")->where(['member_id'=>$member_id])->find();
        $pay_score=0;
        $pay_coin=0;
        if(in_array(1,$pay_method)&&in_array(2,$pay_method)){//积分和金币支付
            $member_coin=$asset['coin'];
            $member_score=$asset['score'];
            if($member_coin>=$pay_amount){//金币充足
                $pay_score=0;
                $pay_coin=$pay_amount-0.01;
                $pay_wx=0.01;
            }else{

                $pay_coin=$member_coin;
                $pay_score=$pay_amount-$member_coin;
                if( $member_score>= $pay_score){
                    $pay_score=$pay_score-0.01;
                    $pay_wx=0.01;
                }else{
                    $pay_score=$member_score;
                    $pay_wx=$pay_amount- $pay_score;
                }

            }
        }elseif(in_array(1,$pay_method)){//积分支付
            $member_score=$asset['score'];
            if($member_score>=$pay_amount){//积分充足
                $pay_score=$pay_amount-0.01;
                $pay_coin=0;
                $pay_wx=0.01;
            }else{
                $pay_score=$member_score;
                $pay_coin=0;
                $pay_wx=$pay_amount-$member_score;
            }

        }elseif(in_array(2,$pay_method)){//金币支付
            $member_coin=$asset['coin'];
            if($member_coin>=$pay_amount){//金币充足
                $pay_score=0;
                $pay_coin=$pay_amount-0.01;
                $pay_wx=0.01;
            }else{
                $pay_score=0;
                $pay_coin=$member_coin;
                $pay_wx=$pay_amount-$member_coin;
            }

        }
        //金额判断

        if(( $pay_wx+ $pay_coin+$pay_score)!=$pay_amount){
            returnJson(-2003,'金额计算有误');
        }
        $tm=time();
        $consume_sn=$tm.mt_rand(10000,99999);
        $score_money=$pay_score;
        $coin_money=$pay_coin;
        $store_member_id=DB::name("store_apply")->where(['sa_id'=>$store_id])->value("member_id");
        if($store_member_id<=0){
            returnJson(-2003,'店铺不存在');
        }
        $orderData=[];
        $orderData['member_id']=$member_id;
        $orderData['store_id']=$store_id;
        $orderData['store_member_id']=$store_member_id;
        $orderData['consume_sn']=$consume_sn;
        $orderData['amount']=$pay_amount;
        $orderData['rebate_rate']=$rebate_rate;
        $orderData['pay_score']=$pay_score;
        $orderData['pay_coin']=$pay_coin;
        $orderData['pay_wx']= $pay_wx;
        $orderData['give_status']= 2;
        $orderData['status']= 2;
        $orderData['create_time']= $tm;
        $orderData['update_time']= $tm;
        Db::startTrans();
        try{

            $orderID=Db::name("shop_pay")->insertGetId($orderData);
            if($orderID<=0){
                throw new Exception("更新失败");
            }
            $orderGoods["order_id"]=$orderID;
            if($score_money>0){//写入积分冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$score_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>1,'log_type_id'=>53,
                        'relation_id'=>$orderID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }
            if($coin_money>0){//写入金币冻结记录
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$coin_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>2,'log_type_id'=>54,
                        'relation_id'=>$orderID,'create_time'=>$tm,'update_time'=>$tm]);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }

            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score-$score_money,frozen_score=frozen_score+$score_money,pay_frozen_score=pay_frozen_score+$score_money,coin=coin-$coin_money,frozen_coin=frozen_coin+$coin_money where member_id=".$input['member_id']." and score>=$score_money and coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }
            $result=$this->orderPay($consume_sn,$member_id,$pay_wx);
            Db::commit();
            returnJson(200,'订单创建成功',$result);
        }catch (Exception $e){
            Db::rollback();
            returnJson(-2004,"订单创建失败");
        }
    }

    /**
     * 取消支付
     */
    public function cancelOrder($input){

        $consume_sn=$input['consume_sn'];
        $member_id=$input['member_id'];
        //获取当前记录
        $payInfo=Db::name("shop_pay")->where(['member_id'=>$member_id,"consume_sn"=>$consume_sn,'status'=>['not in',[1,3]]])->field("sp_id,pay_coin,pay_score")->find();
        $coin_money= $payInfo['pay_coin'];
        $score_money= $payInfo['pay_score'];
        $spID= $payInfo['sp_id'];
        Db::startTrans();
        try {
            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score+$score_money,frozen_score=frozen_score-$score_money,pay_frozen_score=pay_frozen_score-$score_money,coin=coin+$coin_money,frozen_coin=frozen_coin-$coin_money where member_id=".$member_id." and frozen_score>=$score_money  and pay_frozen_score>=$score_money and frozen_coin>=$coin_money ";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }

            $num=Db::name("shop_pay")->where(['member_id'=>$member_id,"consume_sn"=>$consume_sn])->update(['status'=>3]);

            if($num<=0){
                throw new Exception("更新失败");
            }
            $num=Db::name("member_asset_log")->where(['member_id'=>$member_id,'relation_id'=>$spID,"log_type_id"=>['in',[53,54]]])->delete();
            if($num<=0){
                throw new Exception("更新失败");
            }
            Db::commit();
            return ['consume_sn'=>$consume_sn];
        }catch (Exception $e){

           Db::rollback();

            returnJson(-2004,"操作失败");
        }


    }

    /**
     * 微信支付
     */
    public function orderPay($order_sn,$member_id,$pay_wx){
        #获取openid
        $openid = Db::name("member")
            ->field("openid")
            ->where(['member_id'=>$member_id])
            ->value("openid");
        $total_fee=$pay_wx;

        $body ="到店直接消费";
        $notify_url =  request()->domain()."/index.php/applet/Notify/shopOfflinePayment";
        #调取支付接口
        $weixinPay = new WeixinPay($openid, $body, $total_fee, $order_sn,$notify_url);
        // 发起微信支付
        $result = $weixinPay->pay();
        $result['consume_sn']=$order_sn;
        return $result;
    }




}